package com.ls.utils.weixin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ls.utils.ResultData;
import com.ls.utils.http.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 短链接公用类，当前为百度
 */
public class ShortUrlUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShortUrlUtil.class);

    private static final String BAIDU_URL = "https://dwz.cn/api/v3/short-urls";

    /**
     * 请求参数（Headers）
     * 字段	类型	是否必须	说明	示例
     * Dwz-Token	string	必须	用户鉴权信息	获取token
     * Content-Type	string	必须	内容类型	application/json; charset=UTF-8
     * Content-Language	string	非必须	返回错误语言	zh
     * 请求参数（Body）
     * 字段	类型	是否必须	说明	示例
     * LongUrl	string	必须	长网址
     * 免费用户单次最多请求 1 条
     * 付费用户单次最多请求 200 条
     * "http://www.baidu.com"
     * TermOfValidity	string	必须	短网址有效期，目前支持：
     * "long-term"：长期
     * "1-year"：1年
     * "long-term"
     * <p>
     * 响应结果示例
     * <p>
     * {
     * "Code": -99,
     * "ShortUrls": [
     * {
     * "ShortUrl": "https://dwz.cn/de3rp2Fl",
     * "LongUrl": "https://www.baidu.com"
     * },
     * {
     * "Code": -11,
     * "LongUrl": "https://notexsit.dwz.cn",
     * "ErrMsg": "long URL with unsupported host"
     * },
     * ],
     * "ErrMsg": "partial fail"
     * }
     */
    public static ResultData getBaiduUrl(String longUrl) throws IOException {
        //本系统的域名是 www.5gsxt.cn
        String msg;
        if (StringUtils.isBlank(longUrl)) {
            msg = "longUrl 不能为空";
            LOGGER.error(msg);
            return ResultData.failure(msg);
        }
        String param = "[{\"LongUrl\":\"" + longUrl + "\",\"TermOfValidity\":\"1-year\"}]";

        String resultStr = HttpUtils.sendBaiduShortUrlPost(BAIDU_URL, param);
        if (StringUtils.isBlank(resultStr)) {
            msg = "sendBaiduShortUrlPost 返回为 null";
            LOGGER.error(msg);
            return ResultData.failure(msg);
        }
        JSONObject jsonObject = JSONObject.parseObject(resultStr);
        String code = jsonObject.getString("Code");
        if (StringUtils.isBlank(code)) {
            msg = "sendBaiduShortUrlPost code 返回为 null";
            LOGGER.error(msg);
            return ResultData.failure(msg);
        }
        if ("0".equals(code)) {
            String shortUrlsStr = jsonObject.getString("ShortUrls");
            JSONArray jsonArray = JSONArray.parseArray(shortUrlsStr);
            JSONObject info = jsonArray.getJSONObject(0);
            String shortUrl = info.getString("ShortUrl");
            if (StringUtils.isBlank(shortUrl)) {
                msg = "sendBaiduShortUrlPost info shortUrl 返回为 null";
                LOGGER.error(msg);
                return ResultData.failure(msg);
            } else {
                LOGGER.info("longUrl = "+longUrl +" shortUrl = "+shortUrl);
                return ResultData.successData(shortUrl);
            }
        } else {
            switch (code) {
                case "-10":
                    msg = "-10：无效长网址";
                    break;
                case "-11":
                    msg = "-11：长网址不支持缩短";
                    break;
                case "-13":
                    msg = "-13：长网址可能存在安全风险，可申请 安全审核 解决";
                    break;
                case "-14":
                    msg = "-14：长网址数量过多";
                    break;
                case "-20":
                    msg = "-20：有效期设置错误";
                    break;
                case "-21":
                    msg = "-21：长期有效额度不足";
                    break;
                case "-30":
                    msg = "-30：可用点数不足";
                    break;
                case "-91":
                    msg = "-91：域名设置错误";
                    break;
                case "-99":
                    msg = "-99：部分长网址缩短失败";
                    break;
                case "-100":
                    msg = "-100：Token验证失败";
                    break;
                case "-114":
                    msg = "-114：账号需进行 企业实名认证";
                    break;
                default:
                    msg = "getBaiduUrl code =" + code;
                    break;
            }
            LOGGER.error(msg);
            return ResultData.failure(msg);
        }
    }

    public static void main(String[] args) throws IOException {
        getBaiduUrl("http://www.baidu.com");
    }


}
